package com.j1ay.forum.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.j1ay.forum.model.pojo.JwtUser;
import com.j1ay.forum.model.pojo.vo.LoginUserVo;
import com.j1ay.forum.model.pojo.vo.Result;
import com.j1ay.forum.service.UserService;
import com.j1ay.forum.utils.JWTUtils;
import com.j1ay.forum.utils.JwtTokenUtil;
import com.sun.javafx.collections.MappingChange;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author J1ay
 * @Date 2021/12/19 17:16
 * @Description 自定义认证成功处理类
 */

@Component
@Slf4j
public class JwtAuthenticationSuccessHandler  implements AuthenticationSuccessHandler {

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        // 生成token
        log.info(authentication.getName());
        JwtUser jwtUser = (JwtUser) authentication.getPrincipal();
        String realToken = jwtTokenUtil.generateToken(jwtUser.getId().toString());
        log.info(jwtUser.getId().toString());
        redisTemplate.opsForValue().set("TOKEN_" + realToken, JSON.toJSONString(jwtUser), 1, TimeUnit.DAYS);
        log.info("==============" + realToken);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token", realToken);
        LoginUserVo loginUserVo = userService.findUserByUserId(jwtUser.getId());
        System.out.println(loginUserVo);
        jsonObject.put("userInfos", loginUserVo);
        Result result = Result.success(jsonObject);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String json =  JSON.toJSONString(result);
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.getWriter().write(json);
    }
}

